package com.yq.servlet;

import com.sun.deploy.net.HttpResponse;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;


public class IPFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //过滤ip
         HttpServletRequest request = (HttpServletRequest) servletRequest;
         HttpServletResponse response = (HttpServletResponse) servletResponse;
        String remoteAddr = request.getRemoteAddr();
//        if ("192.168.13.12".equals(remoteAddr)){
//            System.out.println("remoteAddr = " + remoteAddr+"不可以访问");
//            response.getWriter().println("no no no !!!!");
//            return;
//        }else {
//            filterChain.doFilter(request,response);
//        }

        //配置文件的形式
        InputStream in = IPFilter.class.getClassLoader().getResourceAsStream("ip.properties");
        Properties properties = new Properties();
        properties.load(in);
        String ips = properties.getProperty("ips");
        String[] split = ips.split(",");
        for (String ip : split) {
            if (ip.equals(remoteAddr)){
                System.out.println("remoteAddr = " + remoteAddr+"不可以访问");
                response.getWriter().println("no no no !!!!");
                return;
            }
        }
        filterChain.doFilter(request,response);




    }

    @Override
    public void destroy() {

    }
}
